<?php
namespace app\massage\model;

use app\BaseModel;
use app\member\model\Integral;
use app\member\model\Level;
use app\member\model\Log;
use app\member\model\Rights;
use longbingcore\wxcore\PospalApi;
use think\facade\Db;

class User extends BaseModel
{
    //定义表名
    protected $name = 'massage_service_user_list';


    /**
     * @author chenniang
     * @DataTime: 2021-08-29 21:18
     * @功能说明:余额
     */
    public function getBalanceAttr($value,$data){

        if(isset($value)&&isset($data['pal_balance'])){

            return round($value+$data['pal_balance'],2);
        }

    }


    /**
     * @author chenniang
     * @DataTime: 2021-10-27 14:49
     * @功能说明:积分
     */
    public function getIntegralAttr($value,$data){

        if(isset($value)&&isset($data['pal_point'])){

            return $value+$data['pal_point'];

        }

    }

    /**
     * @author chenniang
     * @DataTime: 2021-08-29 21:18
     * @功能说明:
     */
    public function getCashAttr($value,$data){

        if(isset($value)){

            return round($value,2);
        }

    }

    /**
     * @author chenniang
     * @DataTime: 2020-09-29 11:04
     * @功能说明:添加
     */
    public function dataAdd($data){

        $data['create_time'] = time();

        $data['status']      = 1;

        $res = $this->insert($data);

        return $res;

    }



    /**
     * @author chenniang
     * @DataTime: 2020-09-29 11:05
     * @功能说明:编辑
     */
    public function dataUpdate($dis,$data){

        $res = $this->where($dis)->update($data);

        return $res;

    }


    /**
     * @author chenniang
     * @DataTime: 2020-09-29 11:06
     * @功能说明:列表
     */
    public function dataList($dis,$page,$mapor=[]){

        $data = $this->where($dis)->where(function ($query) use ($mapor){
            $query->whereOr($mapor);
        })->order('id desc')->paginate($page)->toArray();

        return $data;

    }


    /**
     * @author chenniang
     * @DataTime: 2020-09-29 11:43
     * @功能说明:
     */
    public function dataInfo($dis){

        $data = $this->where($dis)->find();

        return !empty($data)?$data->toArray():[];

    }

    /**
     * @author chenniang
     * @DataTime: 2020-10-27 15:42
     * @功能说明:订单自提码
     */
    public function orderQr($input,$uniacid){

        $data = longbingCreateWxCode($uniacid,$input,$input['page']);

        $data = transImagesOne($data ,['qr_path'] ,$uniacid);

        $qr   = $data['qr_path'];

        return $qr;
    }


    /**
     * @author chenniang
     * @DataTime: 2021-10-27 15:14
     * @功能说明:向银豹同步积分和余额
     */
    public function synBalanceAndPoint($user){

        if(empty($user['customer_uid'])){

            return false;
        }
        //余额
        $balance = $this->where(['id'=>$user['id']])->value('balance');
        //积分
        $integral= $this->where(['id'=>$user['id']])->value('integral');

        if($balance<=0||$integral<=0){

            return false;
        }

        $data = [

            1 => $balance,

            2 => $integral
        ];

        $log = new Log();

        $api = new PospalApi();

        Db::startTrans();

        $res = $this->dataUpdate(['id'=>$user['id']],['balance'=>0,'integral'=>0]);

        if($res==0){

            Db::rollback();

            return ['code'=>500,'msg'=>'同步失败'];
        }
        //增加日志
        foreach ($data as $k=>$v){

            if(!empty($v)){

                $insert = [

                    'uniacid' => $user['uniacid'],

                    'user_id' => $user['id'],

                    'customer_uid' => $user['customer_uid'],

                    'type'  => $k,

                    'value' => $v,

                ];

                $log->dataAdd($insert);
            }

        }
        //修改银豹的积分余额
        $res = $api->updateMemberCash($user['customer_uid'],$balance,$integral);

        if($res['status']){

            Db::rollback();

            return ['code'=>500,'msg'=>$res['messages'][0]];

        }

        Db::commit();

        return true;
    }


    /**
     * @author chenniang
     * @DataTime: 2021-11-08 13:51
     * @功能说明:同步会员到本地
     */
    public function synMemberList($uniacid=1,$update=0){

        $key  = 'syn_member';

        $lock = getCache($key,$uniacid);

        setCache($key,1,60,$uniacid);

        if(!empty($lock)&&$update==0){

            return false;
        }

        $api_model = new PospalApi();

        $member_model = new SynMember();

        $check = 1;

        $post_data = [];

        $member_model->where(['uniacid'=>$uniacid])->delete();

        while ($check==1){

            $data = $api_model->getMemberList($post_data);

            if($data['status']!='success'){

               return [];
            }

            $pageSize = $data['data']['pageSize'];

            $count = count($data['data']['result']);
            //可能有第二页
            if($count>=$pageSize){

                $post_data = $data['postBackParameter'];

            }else{

                $check = 0;
            }

            if(!empty($data['data']['result'])){

                foreach ($data['data']['result']  as $k=>$v){

                    $insert[$k] = [

                        'uid'         => $v['customerUid'],

                        'member_name' => $v['categoryName'],

                        'number'      => $v['number'],

                        'name'        => $v['name'],

                        'phone'       => $v['phone'],

                        'discount'    => $v['discount'],

                        'balance'     => $v['balance'],

                        'point'       => $v['point'],

                    ];


                }

                $member_model->saveAll($insert);

            }

        }

        return true;
    }


    /**
     * @author chenniang
     * @DataTime: 2021-11-08 16:46
     * @功能说明:同步会员余额积分
     */
    public function synMemberCash($uniacid,$user_id){
        //查询所有
        $this->synMemberList($uniacid,1);

        $member_model = new SynMember();

        $dis = [

            'uid' => $user_id
        ];

        $data = $member_model->dataInfo($dis);

        if(empty($data)){

            return ['code'=>500,'msg'=>'请先绑定会员'];

        }

        if(empty($data['balance'])&&empty($data['point'])){

            return ['code'=>500,'msg'=>'你暂无可同步的余额和积分'];

        }

        $api_model = new PospalApi();

        Db::startTrans();
        //扣除银豹平台的余额积分
        $res = $api_model->updateMemberCash($user_id,$data['balance']*-1,$data['point']*-1);

        if($res['status']!='success'){

            Db::rollback();

            return ['code'=>500,'msg'=>$res['messages'][0]];

        }

        $res = $member_model->dataUpdate($dis,['balance'=>0,'point'=>0]);

        if($res==0){

            Db::rollback();

            return ['code'=>500,'msg'=>'同步失败'];

        }
        //给用户加余额积分
        $user_model = new User();

        $user = $user_model->dataInfo(['customer_uid'=>$user_id]);

        $update = [

            'balance' => $user['balance']+$data['balance'],

        ];

        $res = $user_model->dataUpdate(['customer_uid'=>$user_id],$update);

        if($res==0){

            Db::rollback();

            return ['code'=>500,'msg'=>'同步失败'];

        }
        //增加余额日志
        if(!empty($data['balance'])){

            $insert = [

                'uniacid' => $uniacid,

                'user_id' => $user['id'],

                'type'    => 5,

                'add'     => 1,

                'price'   => $data['balance'],

                'before_balance' => $user['balance'],

                'after_balance'  => $user['balance']+$data['balance']
            ];

            $water_model = new BalanceWater();

            $water_model->dataAdd($insert);
        }
        //增加积分日志
        if(!empty($data['point'])){

            $i_model = new Integral();

            $i_model->integralUserAdd($user['id'],$data['point'],$uniacid,2,7);

        }

        Db::commit();

        return true;

    }







    /**
     * @author chenniang
     * @DataTime: 2021-10-27 16:08
     * @功能说明:初次同步会员信息
     */
    public function getMemberInfoOne($user,$member_code){

//        if(!empty($user['customer_uid'])){
//
//            return ['code'=>500,'msg'=>'你已经同步过了'];
//        }

        Db::startTrans();

        $member_model = new SynMember();

        $member_model->where(['user_id'=>$user['id']])->update(['user_id'=>0]);

        $member = $member_model->dataInfo(['uid'=>$member_code]);

        if(empty($member)){

            Db::rollback();

            return ['code'=>500,'msg'=>'未找到会员'];

        }

        if(!empty($member['user_id'])){

            Db::rollback();

            return ['code'=>500,'msg'=>'该会员卡正在被别人使用'];

        }

        $member_model->where(['uid'=>$member_code])->update(['user_id'=>$user['id']]);

        $level_model = new Level();
        //会员等级
        $level = $level_model->levelInfo(['title'=>$member['member_name']]);

        $update = [

            'member_id'    => $member['number'],

            'customer_uid' => $member['uid'],

            'member_level' => !empty($level)?$level['id']:0,

        ];

        $res = $this->dataUpdate(['id'=>$user['id']],$update);
        //给会员权益
        if(!empty($level['id'])){

            $rights_model = new Rights();

            $rights_model->giveRights($level['id'],$user['id']);

        }

        Db::commit();

        return $res;
    }


    /**
     * @author chenniang
     * @DataTime: 2021-10-27 16:24
     * @功能说明:同步会员 修改积分余额
     */
    public function getMemberCashAndPoint($user){

        if(empty($user['customer_uid'])){

            return false;
        }

        $api    = new PospalApi();
        //根据会员号获取会员信息
        $member = $api->getMemberCode($user['customer_uid']);

        if(empty($member['data'])){

            return false;
        }

        $update = [

            'pal_balance' => $member['data']['balance'],

            'pal_point'   => $member['data']['point'],
        ];

        $res = $this->dataUpdate(['id'=>$user['id']],$update);

        return $res;
    }


    /**
     * @author chenniang
     * @DataTime: 2021-10-27 16:40
     * @功能说明:向银豹同步会员信息 然后银豹再向本地同步会员
     */
    public function synMember($user){
        //向银豹同步
        $this->synBalanceAndPoint($user);
        //银豹向本地同步
        $this->getMemberCashAndPoint($user);

        return true;
    }










}